import React from 'react';
import ReactDOM from 'react-dom';

//导入Apollo Client库
import { ApolloClient, ApolloProvider, InMemoryCache, createHttpLink } from '@apollo/client';
import { setContext } from 'apollo-link-context';

//引入全局样式GlobalStyle.js
import GlobalStyle from '/components/GlobalStyle';
//导入路由
import Pages from '/pages';

//配置ARI URI和缓存
const uri = process.env.API_URI;
const httpLink = createHttpLink({ uri });
const cache = new InMemoryCache();

//检查有没有令牌，然后把首部返回给上下文
const authLink = setContext((_, { headers }) => {
  return{
    headers: {
      ...headers,
      authorization: localStorage.getItem('token') || ''
    }
  };
});

//配置Apollo Client
const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache,
  resolvers: {},
  connectToDevTools: true
});

//检查本地有没有令牌
const data = {
  isLoggedIn: !!localStorage.getItem('token')
};

//首次加载时写入缓存数据
cache.writeData({ data });
//重置缓存之后写入缓存数据
client.onResetStore(() => cache.writeData({ data }));

const App = () => {
  return (
    <ApolloProvider client={client}>
        <GlobalStyle />
        <Pages />
    </ApolloProvider>
  );
};

ReactDOM.render(<App />, document.getElementById('root'));